<template>
  <!-- 变更产品 -->
  <a-modal :width="1100" v-model:visible="showEditDialog" title="变更产品" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <a-form ref="formRef" :model="formInfo">
      <a-row style="margin-bottom: 10px">
        <a-col :span="24">
          <a-form-item hide-label>
            <a-textarea v-model="formInfo.remark" placeholder="变更原因" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="6">
          <a-form-item label="报价ID：" label-col-flex="80px">
            <p>{{ formInfo.billNo }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="更新时间：" label-col-flex="100px">
            <p>{{ $setTime(formInfo.gmtWrite) }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="经销商：" label-col-flex="100px">
            <p>{{ formInfo.companyName }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="销售员：" label-col-flex="100px">
            <p>{{ formInfo.createUname }}</p>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="6">
          <a-form-item label="供应商：" label-col-flex="80px">
            <p>{{ formInfo.supplierName }}-{{ formInfo.supplierCode }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="采购员：" label-col-flex="100px">
            <p>{{ formInfo.purchaseUname }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="交期：" label-col-flex="100px">
            <p>{{ formInfo.deliveryDays }}天</p>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="最小起订量：" label-col-flex="100px">
            <p>{{ formInfo.moq }}</p>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="6">
          <a-form-item label="币种：" label-col-flex="80px">
            <p>{{ formInfo.currency }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="发票类型：" label-col-flex="100px">
            <p>{{ invoiceTypeMap[formInfo.invoiceType] }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="parTaxRate" label="票面税率：" label-col-flex="100px">
            <span>{{ formInfo.parTaxRate }}</span>
            <span>%</span>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="退税率：" label-col-flex="100px">
            <span>{{ formInfo.refundTaxRate }}</span>
            <span>%</span>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="product-w" style="margin-top: 20px">
      <div style="margin-bottom: 10px" class="flex-c">
        <a-space style="margin-right: 40px">
          <FilterKeyword ref="filterKeywordRef" :currentItem="filterVal" @search="searchPro" />
          <a-button type="primary" @click="filterKeywordRef.search()">搜索</a-button>
        </a-space>
        <a-space>
          <a-button class="gray-outline" @click="showChooseProductDialog = true">添加报价产品</a-button>
          <a-button class="gray-outline" @click="batchDelete">移除</a-button>
          <p class="warningColor">仅移除产品无需双方同意直接生效</p>
        </a-space>
      </div>
      <a-table class="table-singe-line" ref="tableRef" row-key="sku" :data="filterProductItems" @selection-change="selectColumn" :row-selection="rowSelection" :scroll="{ y: 'calc(84vh - 380px)' }" size="mini" :bordered="false" :pagination="false">
        <template #columns>
          <a-table-column data-index="sort" title="序号" :width="45">
            <template #cell="{ rowIndex }">
              <p>{{ rowIndex + 1 }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="img" title="图片" :width="60">
            <template #cell="{ record }">
              <ImgPopover :src="record.productImg">
                <template #con>
                  <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                </template>
              </ImgPopover>
            </template>
          </a-table-column>
          <a-table-column title="产品名称/类目" :width="180">
            <template #cell="{ record }">
              <TextLimit :rows="1">{{ record.productName }}</TextLimit>
              <p>{{ record.cateName || '--' }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="sku" title="经销商SKU" :width="120">
            <template #cell="{ record }">
              <ShowSpuDetailBySku :val="record.sku" :showLimit="false" />
            </template>
          </a-table-column>
          <a-table-column data-index="spu" title="经销商SPU" :width="120" />
          <a-table-column data-index="ssku" title="供应商SKU" :width="120" />
          <a-table-column data-index="sspu" title="供应商SPU" :width="120" />
          <a-table-column title="操作" :width="60">
            <template #cell="{ record }">
              <a-popconfirm content="确定是否移除?" @ok="singleRemove(record)" type="error">
                <a-button type="text">移除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
  </a-modal>
  <!-- 选择采购产品 -->
  <ChooseQuotationProduct v-if="showChooseProductDialog" :supplierId="formInfo.supplierId" :isShow="showChooseProductDialog" @closed="showChooseProductDialog = false" @success="chooseProduct" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { changePurchaseQuote } from '@/api/purchase'
  import ChooseQuotationProduct from './chooseQuotationProduct.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import FilterKeyword from '@/components/Form/filterKeyword.vue'
  onMounted(() => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })

  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const showEditDialog = ref(props.isShow)
  const formInfo = ref<any>({})
  const invoiceTypeMap = {
    0: '不开票',
    1: '普票',
    2: '专票',
  }
  const filterVal: any = {
    key: 'sku',
    keyItems: [
      { label: '经销商SKU', value: 'sku' },
      { label: '经销商SPU', value: 'spu' },
      { label: '供应商SKU', value: 'ssku' },
      { label: '产品名称', value: 'productName' },
    ],
    keyWidth: '120',
    value: null,
    placeholder: '请输入',
    label: '',
    width: 200,
    isMultiple: true,
  }

  const filterProductItems = ref<Array<any>>([])
  const submitLoading = ref(false)
  const showChooseProductDialog = ref(false)
  const selectIds = ref([])
  const filterKeywordRef = ref()

  // 选中
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 添加初始化数据
  function setDefaultData() {
    formInfo.value = JSON.parse(JSON.stringify(props.currentItem))
    filterItem()
  }
  function filterItem() {
    let valArr = filterVal.value?.split(',') || []
    valArr = valArr.filter((str: string) => str?.trim())
    let key = filterVal.key
    if (!key || !valArr.length) {
      filterProductItems.value = JSON.parse(JSON.stringify(formInfo.value.quoteProducts))
    } else {
      filterProductItems.value = []
      formInfo.value.quoteProducts.forEach((el: any) => {
        if (valArr.includes(el[key])) {
          filterProductItems.value.push(el)
        }
      })
    }
  }
  // 筛选产品列表
  function searchPro(info?: any) {
    filterVal.key = info?.key
    filterVal.value = info?.value
    filterItem()
  }
  function setItemInfoByProduct(item: any) {
    let obj = {
      productId: item.id,
      productImg: item.productPicList?.[0]?.url,
      productName: item.skuName,
      sku: item.sku,
      spu: item.spu,
      cateId: item.category?.id,
      cateName: item.category?.name,
    }
    return obj
  }
  // 添加产品
  function chooseProduct(list: Array<any>) {
    list.forEach((el: any) => {
      if (!formInfo.value.quoteProducts.find((item: any) => el.sku === item.sku)) {
        formInfo.value.quoteProducts.push(setItemInfoByProduct(el))
      }
    })
    filterItem()
  }
  // 单个移除
  function singleRemove(row: any) {
    let index = formInfo.value.quoteProducts.findIndex((el: any) => el.sku === row.sku)
    if (index > -1) {
      formInfo.value.quoteProducts.splice(index, 1)
    }
    filterItem()
  }
  // 批量移除
  function batchDelete() {
    if (!selectIds.value.length) {
      return Message.error('请选择产品')
    }
    Modal.confirm({
      title: '提示',
      content: `请再次确认，移除选中的产品`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: () => {
        selectIds.value.forEach((sku: string) => {
          let index = formInfo.value.quoteProducts.findIndex((el: any) => el.sku === sku)
          if (index > -1) {
            formInfo.value.quoteProducts.splice(index, 1)
          }
        })
        filterItem()
      },
    })
  }
  // 关闭
  function closedDialog() {
    emit('closed')
  }
  // 保存信息
  async function submitData() {
    if (!formInfo.value.quoteProducts.length) {
      Message.error('请最少增加一个关联报价产品产品')
      return false
    }
    let params = JSON.parse(JSON.stringify(formInfo.value))
    params.changeType = 'product'
    const res = await changePurchaseQuote({ changeItems: [params] })
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .arco-row {
    margin-bottom: 0;
  }
  .arco-form-item {
    margin-bottom: 0;
  }
  .add-con {
    height: calc(84vh - 240px);
  }
</style>
